<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!-- 布局 -->
      <el-row :gutter="20" class="wechat_card_head" type="flex">
        <el-col :span="8">
          <!-- 搜索框及添加区域 -->
          <el-input size="medium" placeholder="请输入区域名称" v-model="queryInfo.query" clearable @clear="getAreaList">
            <el-button size="medium" slot="append" icon="el-icon-search" @click="getAreaList"></el-button>
          </el-input>
        </el-col>
        <el-button size="medium" class="btn_head_medium" type="primary" @click="addDialogVisible = true" icon="el-icon-circle-plus-outline">新增</el-button>

        <el-button size="medium" type="danger" @click="removeUserByIds" icon="el-icon-remove-outline">删除</el-button>
        <!-- 全局区域类型筛选框 -->
        <el-select class="select_head_large" size="medium" v-model="areaValue" @change="selectChange" multiple collapse-tags placeholder="按区域类型筛选">
          <el-option label="安保区域" value="0"></el-option>
          <el-option label="消防区域" value="1"></el-option>
          <el-option label="绿化区域" value="2"></el-option>
          <el-option label="保洁区域" value="3"></el-option>
        </el-select>
        <!-- 表格列筛选 -->
        <div class="tools_head">
          <el-popover placement="bottom" trigger="click">
            <el-checkbox-group v-model="colOptions">
              <el-checkbox v-for="item in colSelect" :label="item" :key="item" style="display: block; margin: 10px">
              </el-checkbox>
            </el-checkbox-group>
            <div slot="reference">
              <el-tooltip content="筛选列" placement="bottom">
                <el-button size="small" icon="el-icon-menu"></el-button>
              </el-tooltip>
            </div>
            <el-button size="small" type="text" @click="filterFunHandle('allchecked')">全选</el-button>
            <el-button size="small" type="text" @click="filterFunHandle('cancel')">取消全选</el-button>
          </el-popover>
          <!-- 导出EXCEL -->
          <el-tooltip content="导出excel" placement="bottom">
            <el-button size="small" icon="el-icon-download" style="margin-left: 10px" @click="handleDownload"></el-button>
          </el-tooltip>
        </div>
      </el-row>

      <!-- 区域列表 -->
      <el-table :data="areaList" style="width: 100%" height="85%" size="small" border stripe tooltip-effect="dark" :row-key="
          (row) => {
            return row.id;
          }
        " @selection-change="handleSelectionChange" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }" ref="tableDataRef">
        <el-table-column type="selection" :reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" label="序号" v-if="colData[0].istrue"></el-table-column>
        <el-table-column prop="name" label="区域名称" v-if="colData[1].istrue">
        </el-table-column>
        <el-table-column prop="range" label="范围" v-if="colData[2].istrue" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="area" label="面积" v-if="colData[3].istrue">
        </el-table-column>
        <el-table-column prop="type" label="区域类型" width="100px" v-if="colData[4].istrue" :filters="[
            { text: '安保区域', value: 0 },
            { text: '消防区域', value: 1 },
            { text: '绿化区域', value: 2 },
            { text: '保洁区域', value: 3 },
          ]" :filter-method="filterTag" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type === 0" type="success">安保区域</el-tag>
            <el-tag v-else-if="scope.row.type === 1" type="danger">消防区域</el-tag>
            <el-tag v-else-if="scope.row.type === 2" type="info">绿化区域</el-tag>
            <el-tag v-else type="warning">保洁区域</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="区域地图" v-if="colData[5].istrue" width="130px">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.url" :fit="'contain'" :preview-src-list="[scope.row.url]">
              <div slot="error" class="el-image__error" v-if="scope.row.url == null">
                未上传
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="employeeId" label="区域负责人" v-if="colData[6].istrue"></el-table-column>

        <el-table-column prop="phone" label="联系电话" v-if="colData[7].istrue" width="130px"></el-table-column>
        <el-table-column prop="addUserId" label="添加人" v-if="colData[8].istrue"></el-table-column>
        <el-table-column prop="addTime" label="添加时间" v-if="colData[9].istrue" width="180px">
        </el-table-column>
        <el-table-column prop="memo" label="备注" v-if="colData[10].istrue"></el-table-column>
        <el-table-column label="操作" width="150px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加区域的对话框 -->
      <el-dialog title="添加区域" :visible.sync="addDialogVisible" width="50%" @close="addDialogReset">
        <!-- 内容主题区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" :inline="true">
          <el-form-item label="区域名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="范围" prop="range">
            <el-input v-model="addForm.range"></el-input>
          </el-form-item>
          <el-form-item label="面积" prop="area">
            <el-input v-model.number="addForm.area"></el-input>
          </el-form-item>
          <el-form-item label="区域类型" prop="type">
            <el-select v-model="addForm.type" placeholder="请选择区域类型" class="select">
              <el-option v-for="item in areaInfoList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域地图" prop="url">
            <el-input v-model="addForm.url"></el-input>
          </el-form-item>
          <el-form-item label="区域负责人" prop="employeeId">
            <el-select v-model="addForm.employeeId" placeholder="请选择区域负责人" class="select">
              <el-option v-for="item in employeeinfoList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="addForm.memo"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAreaInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改区域信息的对话框 -->
      <el-dialog title="修改区域信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="editFormRules" :inline="true">
          <el-form-item label="区域名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="范围" prop="range">
            <el-input v-model="editForm.range"></el-input>
          </el-form-item>
          <el-form-item label="面积" prop="area">
            <el-input v-model.number="editForm.area"></el-input>
          </el-form-item>
          <el-form-item label="区域类型" prop="type">
            <el-select v-model="editForm.type" placeholder="请选择区域类型" class="select">
              <el-option v-for="item in areaInfoList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域地图" prop="url">
            <el-input v-model="editForm.url"></el-input>
          </el-form-item>
          <el-form-item label="区域负责人" prop="employeeId">
            <el-select v-model="editForm.employeeId" placeholder="请选择区域负责人" class="select">
              <el-option v-for="item in employeeinfoList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="editForm.memo"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editAreaInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="this.queryInfo.pageNum" :page-sizes="[5, 30, 50, 100]" :page-size="this.queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    // 验证手机号
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的手机
        return callback()
      }
      callback(new Error('请输入合法的手机'))
    }
    return {
      // 获取区域列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      areaList: [],
      //查询到的另一张表的数据
      employeeinfoList: [],
      //
      areaInfoList: [
        { id: 0, value: "安保区域" },
        { id: 1, value: "消防区域" },
        { id: 2, value: "绿化区域" },
        { id: 3, value: "保洁区域" }
      ],
      colData: [
        { title: "序号", istrue: true },
        { title: "区域名称", istrue: true },
        { title: "范围", istrue: true },
        { title: "面积", istrue: true },
        { title: "区域类型", istrue: true },
        { title: "区域地图", istrue: true },
        { title: "区域负责人", istrue: true },
        { title: "联系电话", istrue: true },
        { title: "添加人", istrue: true },
        { title: "添加时间", istrue: true },
        { title: "备注", istrue: true },
      ],
      colOptions: [],//多选框默认全选
      colSelect: [],//所有表头标题,跟多选框组绑定的
      total: 0,
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 添加房产的表单数据
      addForm: {
        name: '',
        range: '',
        area: '',
        type: '',
        url: '',
        employeeId: '',
        phone: '',
        addUserId: '',
        addTime: '',
        memo: ''
      },

      //选中行的id数组
      multipleSelection: [],
      areaValue: [],// 筛选下拉框多选：区域类型
      idsArray: {
        ids: []
      },
      // 查询到的编辑区域信息
      editForm: {},
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
        ],
        range: [
          { required: true, message: '请输入范围', trigger: 'blur' },
        ],
        area: [
          { required: true, message: '请输入面积', trigger: 'blur' },
          { type: 'number', message: '面积必须为数字值' }
        ],
        type: [
          { required: true, message: '请输入区域类型', trigger: 'blur' },
        ],
        url: [
          { required: true, message: '请输入区域地图路径', trigger: 'blur' },
        ],
        employeeId: [
          { required: true, message: '请输入区域负责人', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改区域信息表单的验证规则
      editFormRules: {
        name: [
          { required: true, message: '请输入区域名称', trigger: 'blur' },
        ],
        range: [
          { required: true, message: '请输入范围', trigger: 'blur' },
        ],
        area: [
          { required: true, message: '请输入面积', trigger: 'blur' },
          { type: 'number', message: '面积必须为数字值' }
        ],
        type: [
          { required: true, message: '请输入区域类型', trigger: 'blur' },
        ],
        url: [
          { required: true, message: '请输入区域地图路径', trigger: 'blur' },
        ],
        employeeId: [
          { required: true, message: '请输入区域负责人', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }

    }

  },
  created() {
    this.getAreaList()
    var _this = this;
    for (let i = 0; i < _this.colData.length; i++) {
      _this.colSelect.push(_this.colData[i].title);
      if (_this.colData[i].title == '添加人' || _this.colData[i].title == '添加时间') { //初始化不想展示的列可以放在这个条件里
        continue;
      }
      _this.colOptions.push(_this.colData[i].title);
    }
  },
  watch: {
    // 单选列实现
    colOptions(valArr) {
      var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0); // 未选中
      this.colData.filter(i => {
        if (arr.indexOf(i.title) != -1) {
          i.istrue = false;
        } else {
          i.istrue = true;
        }
      });
      this.$nextTick(() => {
        this.$refs.tableDataRef.doLayout();
      });
    }
  },
  methods: {
    // 获取区域档案列表
    async getAreaList() {
      this.queryInfo = this.getQueryCondition()
      const { data: res } = await this.$http.get('BaseareaAction/getBasicInfos', { params: this.queryInfo })
      if (!res.success) return this.$message.error('获取区域列表失败')
      console.log(res)
      for (var i = 0; i < res.rows.length; i++) {
        res.rows[i].employeeId = res.rows[i].employeeName
      }
      this.areaList = res.rows
      this.total = res.total
      const { data: res0 } = await this.$http.get('EmployeeinfoAction/getBasicInfos')
      this.employeeinfoList = res0.rows
    },

    //点击按钮，添加新区域
    addAreaInfo() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //给隐藏的input输入框中的添加人addUserId赋值
        this.addForm.addUserId = window.sessionStorage.getItem('userId')
        // 添加时间
        this.addForm.addTime = this.dateFormat()
        // console.log(this.addForm.addTime)
        const { data: res } = await this.$http.post("BaseareaAction/addObject", this.addForm)
        if (!res.success) return this.$message.error('添加区域失败')
        //关闭对话框
        this.addDialogVisible = false
        //刷新数据列表
        this.getAreaList()
        this.$message.success('添加区域成功')
      })
    },

    filterTag(value, row) {
      return row.type === value;
    },
    // 展示编辑区域的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.post("BaseareaAction/getObjectById", { id })
      if (!res.success)
        return this.$message.error('查询区域失败')
      this.editForm = res.rows[0]
      // console.log(this.editForm);
      this.editDialogVisible = !this.editDialogVisible
    },

    //点击按钮，修改区域信息
    editAreaInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post("BaseareaAction/updateNoNull", this.editForm)
        if (!res.success) return this.$message.error('修改区域信息失败')
        //关闭对话框
        this.editDialogVisible = false
        //刷新数据列表
        this.getAreaList()
        this.$message.success('修改区域信息成功')
      })
    },
    // 根据id删除区域
    async removeUserById(ids) {
      // 先弹框询问用户是否确定要删除
      const confirmResult = await this.$confirm('此操作将永久删除该区域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 如果点击取消返回的是字符串cancel
      // 如果点击确认返回的是字符串confirm
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.post("BaseareaAction/deleteByIds", { ids })
      console.log(res);
      if (!res.success) {
        return this.$message.error('删除社区失败')
      }
      this.$message.success('删除区域成功')
      // 刷新列表
      this.getAreaList()
    },

    //批量删除
    async removeUserByIds() {
      const rows = this.$refs.tableDataRef.selection;
      if (rows.length === 0) {
        this.$message.warning('请选择需要操作的数据')
        return
      }
      else {
        // 先弹框询问用户是否确定要删除
        const confirmResult = await this.$confirm('此操作将永久删除该街道办, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => {
          return err
        })
        if (confirmResult !== 'confirm') {
          return this.$message.info('取消了删除')
        }
        const { data: res } = await this.$http.post("BaseareaAction/deleteByIds", this.idsArray)
        console.log(res);
        if (!res.success) {
          return this.$message.error('删除街道办失败')
        }
        this.$message.success('删除街道办成功')
        //此时全选框还是选中状态，批量删除后需清除选中状态
        this.$refs.tableDataRef.clearSelection();
        // 刷新列表
        this.getAreaList()
      }

    },
    //导出Excel表
    handleDownload() {
      window.open(axios.defaults.baseURL + '/BaseareaAction/exportDataToExcel?token=' + window.sessionStorage.getItem('token'))
    },
    // 监听修改区域对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //当多选框选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.idsArray.ids = [] //每次点击需清空原本数组的内容
      this.multipleSelection.map(item => { //遍历数组，把id存进自定义的数组里
        this.idsArray.ids.push(item.id)
      })
      this.idsArray.ids = this.idsArray.ids.join(',')
      // console.log(this.idsArray);

    },
    // 监听pageSize改变的事件
    handleSizeChange(newPageSize) {
      // console.log(newPageSize)
      this.queryInfo.pageSize = newPageSize
      // PageSize改变重新拿到区域列表
      this.getAreaList()
    },
    // 监听当前页码改变的事件
    handleCurrentChange(newPageNum) {
      // console.log(newPageNum)
      this.queryInfo.pageNum = newPageNum
      this.getAreaList()
    },
    addDialogReset() {
      // 拿到表单的引用进行重置
      this.$refs.addFormRef.resetFields()
    },
    // 工具栏的各种下拉框筛选监听
    selectChange() {
      this.getAreaList();
    },
    // 全选或取消全选实现
    filterFunHandle(type, currentItem, index) {
      if (type === 'allchecked') { // 全选
        if (this.colSelect.length === 0) {
          this.colData.forEach((result) => {
            this.colSelect.push(result.title)
          })
          this.colOptions = this.colSelect // 复选框置为复选所有值，全部选择

        } else {
          this.colOptions = this.colSelect // 复选框置为复选所有值，全部选择

        }
      } else if (type === 'cancel') { // 取消全选
        this.colOptions = [] // 复选框置为空，全部不选择

      }
    },
    //工具栏的各种下拉框筛选监听
    async selectChange() {
      this.getAreaList()
    },
    //获取工具栏的各类查询条件：搜索框关键词、筛选框值等
    getQueryCondition() {
      //搜索框筛选
      var search = ` basearea.name like "%${this.queryInfo.query}%"`;
      // 下拉框筛选
      var area = '';
      if (this.areaValue.length != 0) {
        area += ` and(`;
        for (var i in this.areaValue) {
          area += ` basearea.type='${this.areaValue[i]}'`
          if (i != this.areaValue.length - 1) {
            area += ` or `
          }
        }
        area += `)`
      }
      this.queryInfo.condition = `${search}${area}`;
      return this.queryInfo;
    }
  }
}
</script>
<style lang="less" scoped>
.el-image /deep/.el-image__error {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #c0c4cc;
  vertical-align: middle;
}
</style>